<?php
namespace app\common\service\member;
use app\common\cache\member\MemberWithdrawalCache;
use app\common\model\member\MemberBillModel;
use app\common\model\member\MemberWithdrawalModel;
use app\common\model\setting\SettingCollectionModel;
use app\common\service\system\SettingService;
use think\facade\Db;

/**
 * 申请提现
 */
class MemberWithdrawalService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'is_disable' => '',
        'member_id' => '',
        'amount' => '',
        'commission' => '',
        'total_amount' => '',
        'name' => '',
        'bank' => '',
        'bank_branch' => '',
        'card_no' => '',
        'wechat_image_id' => '',
        'alipay_account' => '',
        'auth_status' => '',
        'auth_msg' => '',
        'voucher_id' => '',
        'auth_uid' => '',
        'auth_time' => '',
    ];
    /**
     * 申请提现列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MemberWithdrawalModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,is_disable,create_time,update_time,member_id,amount,commission,total_amount,name,bank,bank_branch,card_no,wechat_image_id,alipay_account,auth_status,auth_msg,voucher_id,auth_uid,auth_time,principal_balance,commission_balance,code';
        }
        if (empty($order)) {
            $order = [$pk => 'desc'];
        }
        $with = $append = $hidden = [];
        if (strpos($field, 'wechat_image_id') !== false) {
            $with[]   = $hidden[] = 'wechatImage';
            $append[] = 'wechat_image_url';
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        foreach ($list as $key=>$val){
            //余额计算
            $list[$key]['balance'] =0;
            if (strpos($field, 'principal_balance') !== false && strpos($field, 'commission_balance') !== false) {
                $list[$key]['balance'] =bcadd($val['principal_balance'], $val['commission_balance'],2);
            }
            //转账方式
            $list[$key]['code_title'] ="";
            if(strpos($field, 'code') !== false && $val['code']){
                $list[$key]['code_title'] =SettingCollectionModel::getPayType($val['code'],1);
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 申请提现信息
     *
     * @param int  $id   申请提现id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MemberWithdrawalCache::get($id);
        if (empty($info)) {
            $model = new MemberWithdrawalModel();
            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('申请提现不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            MemberWithdrawalCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 申请提现添加
     *
     * @param array $param 申请提现信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MemberWithdrawalModel();
        $pk = $model->getPk();
        $member_id = member_id(true);
        //账户余额
        $member = Db::name('member')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('member_id',$member_id)
            ->field('member_money,member_commission,alipay_account,wechat_image_id,bank_card_on,name,bank_title,bank_branch')
            ->find();
        if(!$member){
            exception('您的信息丢失，请联系客服');
        }
        //提现账号信息是否完成
        if(!$member['alipay_account'] || !$member['wechat_image_id'] || !$member['bank_card_on'] || !$member['name']){
            exception('请完善提现账号信息');
        }
        $balance = bcadd($member['member_money'], $member['member_commission'],2);
        if($param['amount']>$balance){
            exception('余额不足：'.$param['amount']);
        }
        //提现限制
        $setting = SettingService::info('member_min_withdrawal_amount,member_max_withdrawal_amount,member_withdrawal_commission');
        if($setting['member_min_withdrawal_amount']>0 && $param['amount']<$setting['member_min_withdrawal_amount']){
            exception('提现金额不能小于'.$setting['member_min_withdrawal_amount']);
        }
        if($setting['member_max_withdrawal_amount']>0 && $param['amount']>$setting['member_max_withdrawal_amount']){
            exception('提现金额不能大于'.$setting['member_max_withdrawal_amount']);
        }
        $member_withdrawal_commission = $setting['member_withdrawal_commission'];
        $commission = 0;//手续费
        if($member_withdrawal_commission>0){
            $commission = bcmul($param['amount'],bcdiv($member_withdrawal_commission, 100,4),4);
            $commission = round($commission, 2); // 四舍五入保留两位小数
        }
        $param['create_uid']  = $member_id;
        $param['create_time'] = datetime();
        $param['member_id']  =$member_id;//买家
        $param['total_amount']  =$param['amount'];//提现总额
        $param['balance']  =bcsub($balance, $param['total_amount'],2);//余额
        $param['amount']  =bcsub($param['amount'], $commission,2);//提现金额(不含手续费)
        $param['commission']  =$commission;//提现手续费
        $param['name']  =$member['name'];//提现姓名
        $param['bank']  =$member['bank_title'];//开户银行
        $param['bank_branch']  =$member['bank_branch'];//开户支行
        $param['card_no']  =$member['bank_card_on'];//银行卡号
        $param['alipay_account']  =$member['alipay_account'];//支付宝账号
        $param['wechat_image_id']  =$member['wechat_image_id'];//微信收款码
        $param['auth_status']  =0;//审核状态：0、待审核 1、审核通过 2、审核拒绝 3、提现中
        // 启动事务
        $model->startTrans();
        try {
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            //扣除余额
            MemberService::withdrawal($param['total_amount'],null,$id,'提现流水编号：'.$id);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }
     /**
     * 申请提现修改
     *
     * @param int|array $ids   申请提现id
     * @param array     $param 申请提现信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MemberWithdrawalModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MemberWithdrawalCache::del($ids);
        return $param;
    }
    /**
     * 申请提现删除
     *
     * @param array $ids  申请提现id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MemberWithdrawalModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MemberWithdrawalCache::del($ids);
        return $update;
    }
    /**
     * 查询提现页面所需参数
     * @Author: 易军辉
     * @DateTime:2024-09-27 16:13
     * @param $member_id 买家ID
     * @return array
     */
    public static function getParams($member_id=0)
    {
        $member = Db::name('member')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('member_id',$member_id)
            ->field('member_money,member_commission,alipay_account,wechat_image_id,bank_card_on,name,is_authentication')
            ->find();
        if(!$member){
            exception('您的信息丢失，请联系客服');
        }
        //提现账号信息是否完成
        $is_account = false;
        $is_account_tip = "请完善您的";
        if($member['alipay_account'] && $member['wechat_image_id'] && $member['bank_card_on'] && $member['name']){
            $is_account = true;
        }
        if(!$member['name']){
            $is_account_tip .="姓名、";
        }
        if(!$member['alipay_account']){
            $is_account_tip .="支付宝、";
        }
        if(!$member['wechat_image_id']){
            $is_account_tip .="微信、";
        }
        if(!$member['bank_card_on']){
            $is_account_tip .="银行卡、";
        }
        $is_account_tip .="提现信息";
        //可提现金额
        $balance = bcadd($member['member_money'], $member['member_commission'],2);
        //提现限制
        $setting = SettingService::info('member_min_withdrawal_amount,member_max_withdrawal_amount,member_withdrawal_commission');
        $member_min_withdrawal_amount = $setting['member_min_withdrawal_amount'];
//        if($member_min_withdrawal_amount<=0){
//            $member_min_withdrawal_amount = 0.01;
//        }
        $member_max_withdrawal_amount = $setting['member_max_withdrawal_amount'];
//        if($member_max_withdrawal_amount<=0){
//            $member_max_withdrawal_amount = 'Infinity';
//        }
        $member_withdrawal_commission = $setting['member_withdrawal_commission'];
//        if($member_withdrawal_commission>0){
//            $member_withdrawal_commission=(float)bcdiv($member_withdrawal_commission, 100,4);
//        }
        $is_authentication = $member['is_authentication'];
        return compact('balance','member_min_withdrawal_amount','member_max_withdrawal_amount','member_withdrawal_commission','is_account','is_account_tip','is_authentication');
    }
    /**
     * 审核
     * @Author: 易军辉
     * @DateTime:2024-07-15 17:28
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function auth($ids, $param = [])
    {
        $model = new MemberWithdrawalModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->whereIn('auth_status',[0,3])
            ->where($pk, 'in', $ids)
            ->select();
        if(count($list)<=0){
            exception("未有符合条件的提现记录需要审核");
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->auth_time=datetime();
                $v->auth_uid=user_id();
                switch (intval($param['auth_status'])){
                    case 0://待审核
                        $v->auth_status=0;
                        break;
                    case 1://审核通过
                        $v->auth_status=1;
                        if(!$param['payment_method']){
                            exception('请选择打款方式');
                        }
                        $v->code=$param['payment_method'];
                        //给买家发送消息通知
                        MemberMessageService::add([
                            'title'=>'提现通知',
                            'content'=>"你的提现（支付宝/银行卡/微信）已到账，请查看核实",
                            'member_id'=>$v['member_id'],
                            'data_id'=>$v['id'],
                        ]);
                        break;
                    case 2://审核未通过
                        $v->auth_status=2;
                        $v->auth_msg=$param['auth_msg'];
                        $bill = Db::name('member_bill')
                            ->where('member_id',$v['member_id'])
                            ->where('type',MemberBillModel::getType('WITHDRAWAL',1))
                            ->where('data_id',$v['id'])
                            ->where('money',"<",0)
                            ->where('is_delete',0)
                            ->field('id,money,principal,commission')
                            ->find();
                        if(!$bill || abs($bill['money'])!=$v['total_amount']){
                            exception('ID：'.$v['id']."，退款金额有误请核查");
                        }
                        //退款
                        $commission_res = MemberService::income(
                            $v['member_id'],
                            abs($bill['money']),
                            abs($bill['principal']),
                            abs($bill['commission']),
                            null,//提现失败退款
                            $v['id'],
                            null,
                            $param['auth_msg'].($param['auth_msg']?"，":"")."提现流水编号：".$v['id'],
                            'WITHDRAWAL'
                        );
                        break;
                    case 3://审核中
                        $v->auth_status=3;
                        break;
                }
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        MemberWithdrawalCache::del($ids);
        return $param;
    }
}
